<?php
namespace app\index\controller;
use think\controller;
use think\db;
use think\log;
class Api extends controller
{
	public function sendweibo()
	{
		$this->headfoot();
		if(isset($_REQUEST['text']) )
		{
			include_once( EXTEND_PATH.'weibo/config.php' );
			include_once( EXTEND_PATH.'weibo/saetv2.ex.class.php' );
			if(isset($_SESSION['token']['access_token']))
			{
				$c = new \weibo\SaeTClientV2( WB_AKEY , WB_SKEY , $_SESSION['token']['access_token'] );//3283149014
				$ret = $c->update( $_REQUEST['text'] );	//发送微博
				if ( isset($ret['error_code']) && $ret['error_code'] > 0 )
				{
					echo "<p>发送失败，错误：{$ret['error_code']}:{$ret['error']}</p>";
				}
				else
				{
					echo "<p>发送成功</p>";
				}
			}
		}
	}
	public function SyncWeibo()
	{
		session_start();
		include_once( EXTEND_PATH.'weibo/config.php' );
		include_once( EXTEND_PATH.'weibo/saetv2.ex.class.php' );
		if(isset($_SESSION['token']['access_token']))
		{
			$page = isset($_REQUEST['page']) ? $_REQUEST['page'] : 1;
			$pagenum = isset($_REQUEST['pagenum']) ? $_REQUEST['pagenum'] : 100;
			$c = new \weibo\SaeTClientV2( WB_AKEY , WB_SKEY , $_SESSION['token']['access_token'] );//3283149014
			$ms  = $c->home_timeline($page,$pagenum); // done
			$uid_get =$c->get_uid();
			$uid = $uid_get['uid'];
			$user_message = $c->show_user_by_id( $uid);//根据ID获取用户等基本信息
			$count = 0;
			if($user_message['screen_name']=='google2011')
			{
				foreach($ms['statuses'] as $k=>$v)
				{
					// echo '<pre>';
					// print_r($v);return;
					$exist = DB::query('select id from weibo where mid=?',[$v['mid']]);
					if(!$exist && ($v['user']['id'] == 6006394101 || $v['user']['id'] == 3283149014))
					{
						DB::execute('insert into weibo (uid,mid,text,reposts_count,comments_count,attitudes_count,created_at,isLongText,textLength) values (?,?,?,?,?,?,?,?,?)',[$v['user']['id'],$v['mid'],$v['text'],$v['reposts_count'],$v['comments_count'],$v['attitudes_count'],strtotime($v['created_at']),$v['isLongText'],$v['textLength']]);
						++$count;
					}
				}
			}
			$ret['flag'] = 1;
			$ret['msg'] = htmlspecialchars('本次新增'.$count.'条微博');
			return json_encode($ret);
		}
		else
		{
			$ret['flag'] = 0;
			include_once( EXTEND_PATH.'weibo/config.php' );
			include_once( EXTEND_PATH.'weibo/saetv2.ex.class.php' );
			$o = new \weibo\SaeTOAuthV2( WB_AKEY , WB_SKEY );
			$code_url = $o->getAuthorizeURL( WB_CALLBACK_URL );
			$this->assign('code_url', $code_url);
			$ret['code_url'] = $code_url;
			return json_encode($ret);
			// return $this->fetch('weibo_index');
		}
	}
}